package main

import (
	"commons/record"
	"commons/util/tokenUtil"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"golang.org/x/net/websocket"
	"imi/Instant.chant/connects"
	"imi/Instant.chant/serivce"
	"imi/core"
	"log"
	"net/http"
)

func init() {
	//初始化websocket连接
	connects.Init()
	//日志注册
	record.Register()

	//_ = orm.RegisterDriver("mysql", orm.DRMySQL)
	_ = orm.RegisterDataBase("default", "mysql", "root:s1208923150@tcp(47.52.21.156:3306)/think-cmf?charset=utf8")
	orm.Debug = true

}

func main() {
	record.LogInfo("《《《《《《《《《 启动服务")
	http.Handle("/online", websocket.Handler(func(w *websocket.Conn) {
		Client(w)
	}))
	http.Handle("/chat", websocket.Handler(func(w *websocket.Conn) {
		Client(w)
	}))
	//http.Handle("/Chat", websocket.Handler(Chat))
	//http.Handle("/GroupChat", websocket.Handler(GroupChat))

	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {

		core.Run(writer, request)
	})
	record.LogInfo("《《《《《《《《《 地址：127.0.0.1:9111")
	if err := http.ListenAndServe(":9111", nil); err != nil {
		log.Fatal(err)
	}
}

var userId int = 0

/**
单对单聊
*/
func Chat(w *websocket.Conn) {

}

/**
群聊
*/
func GroupChat(w *websocket.Conn) {

}

func Client(w *websocket.Conn) {
	userId++

	service, _ := serivce.IniConnection(w)

	token := w.Request().URL.Query().Get("token")
	if len(token) <= 0 {
		service.Close()
	}
	userInfo, err := tokenUtil.Parse(token)
	if err != nil {
		service.Close()
	}
	if w != nil {
		connects.Service.Add(userInfo.Id, w)
	}
	for {
		data, _ := service.ReadMessage()
		_ = service.WriteMessage(data)
		//go service.Broadcast(connects.Service.GetLists(), data, false)
	}
}
